//
//  RWPersonInfoViewController.m
//  RedWine
//
//  Created by Liufangfang on 2017/1/2.
//  Copyright © 2017年 HuiBangKe. All rights reserved.
//

#import "RWPersonInfoViewController.h"
#import "FTYPickerView.h"
#import "RWModifyPasswordViewController.h"
#import "RWBindPhoneViewController.h"

#import "FTYPersonInfoPort.h"

@interface RWPersonInfoViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>{

    NSArray *section1Names;
    NSArray *section2Names;
    NSArray *section0Details;
}

@property (nonatomic, strong) UIImageView *avatarV;
@property (nonatomic, strong) UILabel *nickLab;
@property (nonatomic, strong) UILabel *sexLab;
@property (nonatomic, strong) FTYPickerView *sexPickerV;

@end

@implementation RWPersonInfoViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    [self setNavigation];
    [self setPersonInfoUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{
    
    NSString *sex = @"男";
    if (0 == [[FTYUser sharedUser].userSex integerValue]) {
        sex = @"女";
    }
    section1Names = @[@"头像", @"昵称", @"性别"];
    section2Names = @[@"修改密码", @"绑定手机号"];
    section0Details = @[[FTYUser sharedUser].userName, sex];
}

- (void)loadDatas{
    
    
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = @"个人信息";
}

- (void)setPersonInfoUI{
    
    _personInfoTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_personInfoTV];
    _personInfoTV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _personInfoTV.scrollEnabled = NO;
    _personInfoTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _personInfoTV.dataSource = self;
    _personInfoTV.delegate = self;
}

#pragma mark - Config Invoke Methods

#pragma mark - Notificaiton Method

#pragma mark - Notificaiton Invoke Methods

#pragma mark - <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (0 == section) {
        return 3;
    } else {
        return 2;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    if (1 == section) {
        return 8.*FTY_HEIGHT_BASE;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (0 == section && 0 == row) {
        return 100.*FTY_HEIGHT_BASE;
    }
    return 60.*FTY_HEIGHT_BASE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * const personInfoID = @"personInfoID";
    UITableViewCell *personInfoCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:personInfoID];
    personInfoCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    personInfoCell.selectionStyle = UITableViewCellSelectionStyleNone;
    personInfoCell.textLabel.font = FTY_FONTTSIZE(15);
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    switch (section) {
            
        case 0:{
            
            personInfoCell.textLabel.text = section1Names[row];
            
            if (0 == row) {
                
                UIImageView *avatarV = [[UIImageView alloc] init];
                [personInfoCell addSubview:avatarV];
                avatarV.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[FTYUser sharedUser].userAvatar]]];
                avatarV.layer.masksToBounds = YES;
                avatarV.layer.cornerRadius = 70.*FTY_HEIGHT_BASE/2;
                _avatarV = avatarV;
                [avatarV mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.mas_equalTo(personInfoCell.mas_centerY);
                    make.right.mas_equalTo(-40.*FTY_WIDTH_BASE);
                    make.width.height.mas_equalTo(70.*FTY_HEIGHT_BASE);
                }];
            } else {
                    
                UILabel *detailLab = [[UILabel alloc] init];
                [personInfoCell addSubview:detailLab];
                detailLab.text = section0Details[row-1];
                detailLab.textColor = [UIColor blackColor];
                detailLab.font = FTY_FONTTSIZE(14.*FTY_WIDTH_BASE);
                [detailLab sizeToFit];
                if (1 == row) {
                    _nickLab = detailLab;
                } else {
                    _sexLab = detailLab;
                }
                [detailLab mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.mas_equalTo(personInfoCell.mas_centerY);
                    make.right.mas_equalTo(-40.*FTY_WIDTH_BASE);
                }];
            }
            break;
        }
            
        case 1:{
            
            personInfoCell.textLabel.text = section2Names[row];
            
            if (1 == row) {
                
                UILabel *detailLab = [[UILabel alloc] init];
                [personInfoCell addSubview:detailLab];
                detailLab.text = [FTYUser sharedUser].userPhoneNumber;
                detailLab.textColor = [UIColor blackColor];
                detailLab.font = FTY_FONTTSIZE(14.*FTY_WIDTH_BASE);
                [detailLab sizeToFit];
                [detailLab mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.mas_equalTo(personInfoCell.mas_centerY);
                    make.right.mas_equalTo(-40.*FTY_WIDTH_BASE);
                }];
            }
            break;
        }
            
        default:
            break;
    }
    
    //底部线
    UIView *line = [[UIView alloc] init];
    [personInfoCell addSubview:line];
    line.backgroundColor = [UIColor grayColor];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
        make.height.mas_offset(.5*FTY_HEIGHT_BASE);
    }];
    
    return personInfoCell;
}

#pragma mark - <UITableViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    switch (section) {
            
        case 0:{
            
            if (0 == row) {
                
                //设置头像
                [self phoneAlbum];
            }  else if (1 == row) {
            
                //设置昵称
                [self setNickName];
            } else {
            
                //设置性别
                [self setSex];
            }
            break;
        }
            
        case 1:{
            
            if (0 == row) {
                
                //修改密码
                RWModifyPasswordViewController *modifyVC = [[RWModifyPasswordViewController alloc] init];
                [self.navigationController pushViewController:modifyVC animated:YES];
            } else {
            
                //绑定手机号
                RWBindPhoneViewController *bindPhoneVC = [[RWBindPhoneViewController alloc] init];
                [self.navigationController pushViewController:bindPhoneVC animated:YES];
            }
            break;
        }
            
        default:
            break;
    }
}

#pragma mark - Private Invoke Methods

#pragma mark - PhoneAlbum Method

- (void)phoneAlbum{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoLibrary];
    }];
    UIAlertAction *caremaAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self useCarema];
    }];
    UIAlertAction *cancelAciton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertC addAction:caremaAction];
    [alertC addAction:photoAction];
    [alertC addAction:cancelAciton];
    
    [self presentViewController:alertC animated:YES completion:nil];
}

- (void)photoLibrary{
    
    if ([self isPhotoLibraryAvailable]) {
        
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        pickerController.allowsEditing = YES;
        pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        pickerController.mediaTypes = mediaTypes;
        pickerController.delegate = self;
        [self presentViewController:pickerController animated:YES completion:^{
            NSLog(@"Function photoLibrary is calling! Picker View Controller is presented");
        }];
    }
}

- (void)useCarema{
    
    if ([self isCaremaAvailable] && [self doesCaremaSupportTakingPhotos]) {
        
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        pickerController.allowsEditing = YES;
        if ([self isFrontCaremaAvailable]) {
            pickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        pickerController.mediaTypes = mediaTypes;
        pickerController.delegate = self;
        [self presentViewController:pickerController animated:YES completion:^{
            NSLog(@"Function useCarema is calling! Picker View Controller is presented");
        }];
    }
}

#pragma mark - <UIImagePickerControllerDelegate>

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取相册图片
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    _avatarV.image = img;
    [self postAvatarImage:img];
}

//从后台获取头像并保存
- (void)postAvatarImage:(UIImage *)avatarImage{
 
    FTYUser *user = [FTYUser sharedUser];
     [[FTYHTTPManager sharedManager] POST:[NSString stringWithFormat:@"http://59.110.60.173/shop/ybkapi.php?act=ybkapi&op=updatememberinfo&member_id=%@&token=%@", user.userID, user.userToken] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
     
         NSData *imageData = UIImageJPEGRepresentation(avatarImage, 0.5);
         [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"image.jpg" mimeType:@"image/jpeg"];
     } progress:^(NSProgress * _Nonnull uploadProgress) {
     
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
         
         FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
         baseModel = [FTYBaseModel mj_objectWithKeyValues:responseObject];
         FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
         
         if (0 == errorInfo.errorcode) {
             
             //保存信息
             [[FTYUser sharedUser] setUserAvatar:responseObject[@"info"][@"member_avatar"]];
         } else {
             [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
         NSLog(@"个人信息修改error：%@", error);
     }];

}
 
- (void)saveInfo{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshLoginSuccessNotification" object:nil];
}

#pragma mark - Nick Name Method

- (void)setNickName{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"修改昵称" message:nil
                                                             preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"保存昵称");
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消修改昵称");
    }];
    
    [alertC addAction:okAction];
    [alertC addAction:cancelAction];
    [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = @"请输入昵称";
        textField.delegate = self;
        [textField addTarget:self action:@selector(nicknameTextFieldAction:) forControlEvents:UIControlEventEditingChanged];
    }];
    
    [self presentViewController:alertC animated:YES completion:nil];
}

- (void)nicknameTextFieldAction:(UITextField *)textField{
    
    NSString *nick = textField.text;
    _nickLab.text = nick;
    [FTYPersonInfoPort requestModifyPersonInfoKey:@"member_name" personInfoValue:nick view:self.view];
}

#pragma mark - Sex Method

- (void)setSex{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    FTYPickerView *sexPickerV = [[FTYPickerView alloc] initWithFrame:CGRectMake(20*FTY_WIDTH_BASE, -55*FTY_HEIGHT_BASE, CGRectGetWidth(alertC.view.frame), 150*FTY_HEIGHT_BASE)];
    [alertC.view addSubview:sexPickerV];
    sexPickerV.titleForRowArr = @[@"男", @"女"];
    _sexPickerV = sexPickerV;
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *sex = sexPickerV.currentTitle;
        _sexLab.text = sex;
        [FTYPersonInfoPort requestModifyPersonInfoKey:@"member_sex" personInfoValue:sex view:self.view];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消修改性别");
    }];
    
    [alertC addAction:okAction];
    [alertC addAction:cancelAction];
    
    [self presentViewController:alertC animated:YES completion:nil];
}

#pragma mark - Carema API

- (BOOL)isCaremaAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL)isFrontCaremaAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL)isRearCaremaAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL)doesCaremaSupportTakingPhotos{
    return [self caremaSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

#pragma mark - PhotoLibrary API

- (BOOL)isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL)canUserPickPhotosFromPhotoLibrary{
    return [self caremaSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL)canUserPickVideosFromPhotoLibrary{
    return [self caremaSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL)caremaSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    
    __block BOOL result = NO;
    if(0 == [paramMediaType length]){
        NSLog(@"Media is empty.");
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *mediaType = obj;
        if ([mediaType isEqualToString:paramMediaType]) {
            result = YES;
            *stop = YES;
        }
    }];
    return result;
}

@end
